﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SQLToolsCore
{
    public partial class TemplateEditer : Form
    {
        private int _width, _height;
        private string _path;

        public TemplateEditer()
        {
            InitializeComponent();
            _width = this.Width;
            _height = this.Height;

            InitContent(string.Empty);
        }

        //自定义模版编辑器
        public TemplateEditer(string path)
        {
            InitializeComponent();
            _width = this.Width;
            _height = this.Height;
            _path = path;

            InitContent(path);
        }

        //作为提示框
        public TemplateEditer(int width, int height, string content,
            string title = "", TipIconType tipIconType = TipIconType.Info, bool enable = true, bool enresize = false)
        {
            _width = this.Width;
            _height = this.Height;
            InitializeComponent();

            this.Width = width;
            this.Height = height;
            this.richTextBox1.Width = this.ClientSize.Width;
            this.richTextBox1.Height = this.ClientSize.Height - 35;

            if (!enresize)
            {
                this.MaximumSize = new Size(width, height);
                this.MinimumSize = new Size(width, height);
            }
            if (!string.IsNullOrWhiteSpace(title))
            {
                this.Text = title;
            }

            this.Icon = tipIconType switch
            {
                TipIconType.Info => Properties.Resources._ic_info,
                TipIconType.Warn => Properties.Resources._ic_warn,
                TipIconType.Erro => Properties.Resources._ic_erro,
                _ => Properties.Resources._ic_info,
            };

            richTextBox1.Font = new Font("微软雅黑", 12);
            richTextBox1.Text = content;
            richTextBox1.Enabled = enable;

            this.menuStrip1.Visible = false;
            this.richTextBox1.Location = new Point(this.richTextBox1.Location.X, this.richTextBox1.Location.Y - 31);
            this.richTextBox1.Height += 31;
        }

        protected void FormResizeEvent(object o, EventArgs e)
        {
            int offsetWidth = this.Width - _width;
            int offsetHeight = this.Height - _height;

            this.richTextBox1.Width += offsetWidth;
            this.richTextBox1.Height += offsetHeight;

            _width = this.Width;
            _height = this.Height;
        }

        public void InitContent(string path)
        {
            richTextBox1.Font = new Font("Consolas", 12);
            richTextBox1.Text = LoadContent(path);
            //SetRichTexBoxColor();
        }

        public static string LoadContent(string path)
        {
            string rtnStr = string.Empty;

            using (StreamReader sr = new(path, Encoding.Default))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    rtnStr += line.ToString() + "\n";
                }
                sr.Close();
            }
            return rtnStr;
        }

        #region 设置自定义模版颜色
        private static readonly List<string> _codeKeyChar = new() { "&/notdate&", "&notdate&", "&loop&" };

        private void SetRichTexBoxColor()
        {
            var setIndexs = GetIndexFormText(richTextBox1.Text);

            setIndexs.ForEach(x =>
            {
                richTextBox1.Select(x[0], x[1]);
                richTextBox1.SelectionColor = Color.DarkBlue;
            });

            richTextBox1.SelectionStart = richTextBox1.Text.Length;
        }

        private static List<int[]> GetIndexFormText(string text)
        {
            var lst = new List<int[]>();
            int startIndex = 0;
            int endIndex = 0;
            string tempStr;
            while (endIndex < text.Length)
            {
                endIndex++;
                tempStr = text[startIndex..endIndex];
                if (MatchKeyChar(tempStr, true))
                {
                    if (MatchKeyChar(tempStr, false))
                    {
                        lst.Add(new int[] { startIndex, endIndex });
                        startIndex = endIndex;
                    }
                }
                else
                {
                    startIndex = endIndex;
                }
            }

            return lst;
        }

        private static bool MatchKeyChar(string str, bool fuzzyFlag)
        {
            return fuzzyFlag ? _codeKeyChar.Any(x => x.Contains(str)) : _codeKeyChar.Any(x => x.Equals(str));
        }
        #endregion

        private void ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            FileStream fs = new(_path, FileMode.Create, FileAccess.Write);
            using (StreamWriter sw = new(fs, Encoding.Default))
            {
                sw.Write(this.richTextBox1.Text);
                sw.Close();
            }
            MessageBox.Show("保存成功！");
        }

        private void ToolStripMenuItem3_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new();
            saveFileDialog.Filter = "(*.txt)|*.txt|(*.*)|*.*";
            saveFileDialog.FileName = "文件" + DateTime.Now.ToString("yyyyMMddHHmm") + ".txt";
            //将日期时间作为文件名
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                StreamWriter streamWriter = new(saveFileDialog.FileName, true);
                streamWriter.Write(this.richTextBox1.Text);
                streamWriter.Close();
            }
        }

        private void ToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            new TemplateEditer(700, 300, "提示一下帮助信息", "帮助").Show();

        }

    }

    public enum TipIconType
    {
        Info = 1,
        Warn = 2,
        Erro = 3
    }
}
